<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="spu名称">
        <el-input placeholder="请输入spu名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="spu描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="描述"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="spu图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option :value="`${unSelect.id}:${unSelect.name}`" :label="unSelect.name" v-for="unSelect in unSelectSaleAttr" :key="unSelect.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" style="margin-left: 10px" :disabled="!attrIdAndAttrName" @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table
          style="width: 100%; margin-top: 10px"
          border
          :data="spu.spuSaleAttrList"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width">
          </el-table-column
          ><el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <!--@close="handleClose(tag)"-->
              <el-tag
                :key="tag.id"
                v-for="(tag,index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index,1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!--@keyup.enter.native="handleInputConfirm(row)"-->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <!--@click="showInput"-->
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加 +</el-button
              >
            </template> </el-table-column
          ><el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row,$index}">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index,1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      spu: {
        category3Id: 0,
        description: "",
        spuName: "",
        tmId: '',
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      },
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //spu图片数据
      saleAttrList: [], //销售属性数据
      attrIdAndAttrName:'',//收集未选择的销售属性id
    };
  },
  methods: {
    //照片墙删除图片
    handleRemove(file, fileList) {
      //file代表删除的图片
      //filelist代表删除后剩余的其他图片
      this.spuImageList = fileList;
    },
    //照片墙图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //照片墙上传成功的回调
    handleSuccess(response,file,fileList){
      this.spuImageList = fileList;
    },
    //初始化spu的数据
    async initSpuData(row) {
      //获取spu信息的数据
      let spuResult = await this.$API.spu.reqSpu(row.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      //获取品牌信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      //获取图片
      let spuImageResult = await this.$API.spu.reqSpuImageList(row.id);
      if (spuImageResult.code == 200) {
        let listArr = spuImageResult.data;
        listArr.forEach((element) => {
          element.name = element.imgName;
          element.url = element.imgUrl;
        });
        this.spuImageList = listArr;
      }
      //获取平台全部销售属性
      let SaleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (SaleResult.code == 200) {
        this.saleAttrList = SaleResult.data;
      }
    },
    //添加新的销售属性
    addSaleAttr(){
      //把收集到的销售属性数据分割
      const [baseSaleAttrId,saleAttrName] = this.attrIdAndAttrName.split(":");
      let newSaleAttr = {baseSaleAttrId,saleAttrName,spuSaleAttrValueList:[]};
      this.spu.spuSaleAttrList.push(newSaleAttr);
      this.attrIdAndAttrName = '';
    },
    //添加属性值回调
    addSaleAttrValue(row){
      this.$set(row,"inputVisible",true);
      this.$set(row,"inputValue",'');
    },
    //添加属性值input失去焦点
    handleInputConfirm(row){
      const {baseSaleAttrId,inputValue} = row;
      //新增的销售属性值不能为空
      if(inputValue.trim() == ''){
        this.$message.error("属性值不能为空");
        return ;
      }
      //属性值不能重复
      let ok = row.spuSaleAttrValueList.every((element)=>{
        return element.saleAttrValueName!=inputValue;
      });
      if(!ok){
        this.$message.error("属性值不能重复");
        return;
      }
      let newSaleAttrValue = {baseSaleAttrId,saleAttrValueName:inputValue};
      row.spuSaleAttrValueList.push(newSaleAttrValue);
      row.inputVisible = false;
    },
    //保存按钮
    async addOrUpdateSpu(){
      //整理参数
      this.spu.spuImageList = this.spuImageList.map((element)=>{
        return{
          imgName:element.name,
          imgUrl:(element.response&&element.response.data)||element.url,
        }
      })
      let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu);
      if(result.code==200){
        this.$message({type:"success",message:"保存成功"});
        //通知父组件回到场景0
        this.$emit("changeScene",{scene:0,flag:this.spu.id?"修改":"添加"});
      }
      //清除数据
      Object.assign(this._data,this.$options.data());
    },
    //取消按钮
    cancel(){
      this.$emit('changeScene', {scene:0,flag:''});
      //清理数据
      Object.assign(this._data,this.$options.data());
    },
    //点击添加spu按钮，发请求
    async addSpuData(c3Id){
      this.spu.category3Id= c3Id;
      //获取品牌信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      //获取平台全部销售属性
      let SaleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (SaleResult.code == 200) {
        this.saleAttrList = SaleResult.data;
      }
    },
  },
  computed:{
    //还没选择的销售属性
    unSelectSaleAttr(){
      let result = this.saleAttrList.filter((item1)=>{
        //如果当前这个所有属性和每一个本身已经选择的属性都不同，说明当前这个属性没有被选择
        return this.spu.spuSaleAttrList.every((item2)=>{
          return item1.name!=item2.saleAttrName;
        })
      })
      return result;
    }
  }
};
</script>

<style>
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style></style>
